<template>
  <div class="data-statistics">
    <ContentForm name="缺陷数量与时间的关系">
      <div slot="searchform" class="form-top">
        <form action="">
          <p class="form-top-p">
            <el-select v-model="listQuery.unitDeptCode" clearable placeholder="选择单位" @change="changeDept" @clear="delDept">
              <el-option
                v-for="item in filterData.deptOption"
                :key="item.deptNo"
                :label="item.deptName"
                :value="item.deptNo" />
            </el-select>
          </p>
          <p class="form-top-p">
            <el-select v-model="listQuery.lineId" clearable placeholder="选择线路">
              <el-option
                v-for="item in filterData.lineOption"
                :key="item.seclineId"
                :label="item.seclineName"
                :value="item.seclineId" />
            </el-select>
          </p>
          <p class="form-top-p">
            <el-date-picker
              v-model="listQuery.dateList"
              class="input-long"
              type="monthrange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
              value-format="yyyy-MM" />
          </p>
          <p class="form-top-p">
            <el-button type="primary" size="mini" icon="el-icon-search" @click="getlist">查询</el-button>
          </p>
        </form>
      </div>
      <div slot="valueform" v-loading="loading" class="value-form" style="padding-top:4px;">
        <div id="linebar-chart" style="height:calc(100% - 2rem);width:100%;" />
      </div>
    </ContentForm>
  </div>
</template>

<script>
import { DefectAndTimeRelation } from '@/api/cms/data-statistics'
import { findManageUnitDeptList, getLineList } from '@/api/platform'
import echarts from 'echarts'
export default {
  name: 'DefectRelation',
  components: {
  },
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 8.64e6
        }
      },
      myChart: null,
      loading: false,
      alldata: {},
      listQuery: {
        unitDeptCode: '',
        lineId: '',
        dateList: []
      },
      filterData: {
        deptOption: [],
        lineOption: []
      }
    }
  },
  watch: {
  },
  mounted() {
    // 获取当前年月,选择默认时间段 12个月
    const year = new Date().getFullYear()
    const month = new Date().getMonth()
    const startdata = (Number(month) + 2) > 12 ? (Number(year) - 1) + '-01' : (Number(month) + 2) < 10 ? (Number(year) - 1) + `-0${(Number(month) + 2)}` : (Number(year) - 1) + `-${(Number(month) + 2)}`
    const enddata = (Number(month) + 1) < 10 ? year + `-0${(Number(month) + 1)}` : year + `-${(Number(month) + 1)}`
    this.listQuery.dateList = [startdata, enddata]
    // 获取单位 deptList
    findManageUnitDeptList({}).then(response => {
      var resData = response.data
      for (var i in resData) {
        if (resData[i].deptNo === '001200') {
          resData.splice(i, 1)
        }
      }
      this.filterData.deptOption = Object.freeze(resData)
    })
    this.getlist()
    // 监听屏幕变化，改变echarts尺寸
    const _this = this
    window.addEventListener('resize', function() {
      _this.$nextTick(_ => {
        _this.myChart.resize()
      })
    })
  },
  beforeDestroy() {
    if (!this.myChart) {
      return
    }
    this.myChart.dispose()
    this.myChart = null
  },
  methods: {
    changeDept(val) {
      this.listQuery.lineId = ''
      this.filterData.lineOption = []
      getLineList({ unitDeptCode: val }).then(response => {
        // console.log('线路下拉框', response)
        this.filterData.lineOption = Object.freeze(response.data)
      })
    },
    delDept() {
      this.listQuery.lineId = ''
      this.filterData.lineOption = []
    },
    getlist() {
      if (!this.listQuery.dateList || !this.listQuery.dateList[1]) {
        this.$alert('请选择时间', '提示', {
          confirmButtonText: '确定'
        })
        return
      }
      var obj = {
        lineId: this.listQuery.lineId,
        unitDeptCode: this.listQuery.unitDeptCode,
        startMonth: this.listQuery.dateList[0],
        endMonth: this.listQuery.dateList[1]
      }
      this.alldata = {}
      this.loading = true
      DefectAndTimeRelation(obj).then(res => {
        this.loading = false
        this.alldata = res.data
        this.handleData()
      })
    },
    handleData() {
      var echartsData = {
        title: '',
        legend: ['1C', '2C', '3C', '4C'],
        xAxisData: [],
        series: [],
        maxnum: 0
      }
      echartsData.title = '缺陷趋势图'
      this.alldata.count.forEach(item => {
        echartsData.xAxisData.push(item.month)
        item.name = '缺陷总数'
      })
      for (const item of echartsData.legend) {
        const obj = {
          name: item,
          type: 'bar',
          data: []
        }
        this.alldata[item].forEach(item => {
          obj.data.push(item.value)
        })
        echartsData.series.push(obj)
      }
      echartsData.legend.push('缺陷总数')
      const obj = {
        name: '缺陷总数',
        type: 'line',
        lineStyle: {
          color: '#409eff'
        },
        itemStyle: {
          color: '#409eff'
        },
        yAxisIndex: 1,
        data: []
      }
      this.alldata.count.forEach(item => {
        obj.data.push(item.value)
      })
      echartsData.maxnum = Math.max(...obj.data)
      echartsData.series.push(obj)
      this.getecharts(echartsData)
    },
    getecharts(echartsData) {
      const chart = echarts.init(document.getElementById('linebar-chart'), 'light')
      this.myChart = chart
      chart.setOption({
        // color: ['#409EFF', '#cccccc'],
        title: {
          text: echartsData.title,
          left: 'center',
          top: 10
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        legend: {
          data: echartsData.legend,
          bottom: 0
        },
        grid: {
          left: '40',
          right: '40',
          bottom: '40',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: echartsData.xAxisData,
            axisPointer: {
              type: 'shadow'
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '条',
            min: 0,
            max: echartsData.maxnum
          },
          {
            type: 'value',
            name: '缺陷总数和(条)',
            min: 0,
            max: echartsData.maxnum
          }
        ],
        series: echartsData.series
      })
    }
  }
}
</script>

<style scoped lang="scss">
  .input-long{
    width: 280px;
    ::v-deep .el-input__icon{
      line-height: 22px;
    }
  }
</style>
